package com.moyun.finance.utils;

import com.moyun.finance.entity.OrgUser;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查每个到来的请求对应的session域中是否有登录标识
        OrgUser user = (OrgUser) request.getSession().getAttribute("loginUser");
        if (null == user) {
//            response.sendRedirect("/login");
//            returnJson(response,"未登录或登录超时!");
            returnJson(response, "{\"code\":601,\"msg\":\"未登录或登录超时!\"}");
            return false;
        }
        String userName = user.getUserName();
        System.out.println("当前用户已登录，登录的用户名为： " + userName);
        return true;
    }


    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}
